package com.ojoin.weixin.core.oauth2.util;

import java.util.Map;

import com.ojoin.trade.common.utils.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.weixin.core.model.AccessToken;
import com.ojoin.weixin.core.model.Result;

/**
 * 微信企业号调用类 {"errcode":0,"errmsg":"ok"} 此结果表示调用方法成功返回
 * 
 * @author Sunlight
 * 
 */
public class WeixinUtil {

	private static final Logger logger = LoggerFactory.getLogger(WeixinUtil.class);

	private static AccessToken accessToken=null;
	/**
	 * 获取企业号AccessToken
	 * 
	 * @param CorpID
	 * @param CorpSecret
	 * @return
	 */
	public static AccessToken getAccessToken(String CorpID, String CorpSecret) {
		if(null==accessToken||(null!=accessToken&&!accessToken.isExpired())){
			accessToken = WechatAccessToken.getAccessToken(CorpID,CorpSecret, 1);
		}
		return accessToken;
	}

	/**
	 * OAuth2验证接口根据code获取成员信息
	 * 
	 * @param token
	 * @param code
	 * @param AgentID
	 * @return
	 */
	public static Result<String> oAuth2GetUserByCode(String token, String code,
			int AgentID) {
		Result<String> result = new Result<String>();
		Map jo = WechatOAuth2.getUserByCode(token, code, AgentID);
		if (jo != null) {
			try {
				String userId = (String)jo.get("UserId");
				if (userId != null && userId.length() > 0) {
					result.setErrmsg("");
					result.setErrcode("0");
					result.setObj(userId);
				} else {
					result.setErrmsg((String)jo.get("errmsg"));
					result.setErrcode(String.valueOf(jo.get("errcode")));
				}

			} catch (Exception e) {

				LogUtils.error(logger, e,"获取成员信息异常"+e.getMessage());

				String OpenId = (String)jo.get("OpenId");
				if(null!=OpenId){
					result.setErrmsg("");
					result.setErrcode("1");
					result.setObj(OpenId);
				}else{
					result.setErrmsg("accessToken 超时......");
					result.setErrcode("42001");
				}
			}
		}
		return result;
	}
}
